<?php

namespace My\Controller;

use Utuo\BackgroundController;
use Utuo\Phpass;

class LoginController extends BackgroundController {
	
	// 手机端注册
	public function mobileRegisterAction() {
		$this->display();
	}
	
	// 注册
	public function registerAction(){
		layout(false);
		$customerManagerConfig = $this->getManagerConfig();
		$this->display($customerManagerConfig['tpl']);
	}
	
	// 登录地址
	public function indexAction() {
		layout(false);
		// 客户后台显示合作商的信息
		// 暂时这样处理，还有更好的方式
		$partnerLabel = I('p');
		if ($partnerLabel){
		    $partner = M('Partner')->where(array('label'=>$partnerLabel))->find();
		    $this->assign('partner',$partner);
		    $this->display($partner['label']);
		} else {
    		$customerManagerConfig = $this->getManagerConfig();
    		$this->display($customerManagerConfig['tpl']);
		}
	}
	
	// 保存用户
	public function saveCustomerAction() {
		$verify = I('verify');
		// 验证码
		if ($_REQUEST['from']!='mobile' and !check_verify($verify, 1)) {
			$this->ajaxError("验证码不正确");
		}
		
		$d = D("customer");
		if ($d->create()) {
			if (!empty($d->password)) {
				$d->password = Phpass::hash($d->password);
			} else{
				$this->ajaxError("密码不能为空!");
			}
			$d->begin_time = time();
			$d->end_time = strtotime("+7 day");
			$d->partner = 15;
			$dd = clone $d;
			if ($cid = $d->add()) {
				 $admin = array(
					'cid' => $cid,
					'name' => $dd->name,
					'email' => $dd->email,
					'password' => $dd->password,
					'last_login_time' => 0,
					'last_login_ip' => '',
					'login_count' => 0,
					'is_role' => 0,
					'is_super' => 1,
				);
				$id = M("CustomerAdmin")->add( $admin );
				if (false !== $id ) {
					$admin['id'] = $id;
					$this->authMenu($id);
					//$this->saveLogin($admin);
					$this->ajaxSuccess('注册成功!');
				} else {
					$this->ajaxError('注册失败!');
				}
			}
		} else {
			$this->ajaxError($d->getError());
		}
	}
	
	// 授权默认菜单
	private function authMenu( $adminCid ) {
		$m = M("CustomerMenuManager");
		$menu = array('1','10','26','7','60', // 微信设置
			'89','90','91','92','93','96','97','98','99', // 分销商城
			'28','29','30','31','51','53','54','55', // 官网
			'12','101', // 官网
		);
		foreach ( $menu as $v ) {
			$menus[] = array(
					'admin_cid' => $adminCid,
					'menu_id' => $v,
			);
		}
		$m->addAll( $menus );
	}
	
	// 登录提交
	public function loginAction() {
		$email = I('email', '', 'htmlspecialchars');
		$password = I('password', null, false);
		$verify = I('verify');
		
		// 验证码
		if(!APP_DEBUG){
			if (!check_verify($verify, 1)) {
				$data['error'] = 1;
				$data['message'] = '验证码不正确';
				$this->ajaxReturn($data);
			}
		}


		$admin = M('customerAdmin a')->join("__CUSTOMER__ b on a.cid=b.id", "LEFT")->where("a.email='%s' and a.is_deleted=0", $email)->field('a.*,b.name as customerName,b.partner,b.last_login_time as u_login_count,b.begin_time,b.end_time')->find();
		$admin and $id = $admin['cid'];
		$adminId = $admin['id'];
		if ( $admin ) {
			$admin['name'] = $admin['customerName'];
		}
		$now = time();
		
		if (empty($admin)) {
			$data['error'] = 1;
			$data['message'] = '登录账号不存在';
		} elseif($now > $admin['end_time']) {
			$data['error'] = 1;
			$data['message'] = '登录账号已过期';
		} else {
			if (Phpass::check($password, $admin['password'])) {
				if ($admin['status'] == 0) {
					$data['error'] = 1;
					$data['message'] = '禁止登录';
				} else {
					$data['error'] = 0;
					$data['message'] = '登录成功';
					$this->saveLogin($admin);
				}
			} else {
				$data['error'] = 1;
				$data['message'] = '登录密码不正确';
			}
		}
		$this->ajaxReturn($data);
	}
	
	// 退出登录
	public function logoutAction() {
		$this->setLogout();
		header('Content-Type:text/html; charset=utf-8');
		session('loginPartner',null);
		$this->redirect('My/login/index', array('p'=>I('p'),'pid'=>I('pid',null,'intval')), 1, '已经退出，转到登录页面……');
	}
	
	// 验证码
	public function verifyAction() {
		parent::createVerify(1);
	}
	
	// 保存登录信息
	private function saveLogin($admin) {
		$this->setLogin($admin['cid'], $admin['name'], array(C("USER_AUTH_KEY")=>$admin['id'], 'pid' => $admin['partner']));
			
		M('customer')->where("id=" . $admin['cid'])->save(array(
			'last_login_time' => time(),
			'last_login_ip' => get_client_ip(),
			'login_count' => $admin['u_login_count'] + 1,
		));
			
		M('customerAdmin')->where("id=" . $admin['id'])->save(array(
			'last_login_time' => time(),
			'last_login_ip' => get_client_ip(),
			'login_count' => $admin['login_count'] + 1,
		));
	}
}